var sceneReadyBehavior = require('../../behavior-scene/scene-ready');

Page({
  behaviors:[sceneReadyBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    machineName: '',
    axisName: '',
    
    // 计算记录数据
    recordData: null,
    
    // 请求参数
    formData: {},
    
    // 计算结果
    calcResults: {},
    
    // 选择的电机信息
    selectedMotor: {},
    
    // 图表数据
    speedChartData: {},
    forceChartData: {},
    
    // 页面状态
    hasData: false,
    errorMessage: '',

    // 模型信息
    modelUrl: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('搜索详情页面加载, 参数:', options);
    if (options.id) {
      // 通过ID直接查询记录
      this.searchCalculationRecordById(options.id);
    } else if (options.machineName && options.axisName) {
      this.setData({
        machineName: decodeURIComponent(options.machineName),
        axisName: decodeURIComponent(options.axisName)
      });
      
      // 查询计算记录
      this.searchCalculationRecord();
    } else {
      this.setData({
        loading: false,
        errorMessage: '缺少必要参数'
      });
    }
  },

  /**
   * 通过ID搜索计算记录
   */
  async searchCalculationRecordById(recordId) {
    try {
      wx.showLoading({
        title: '加载中...'
      });

      const result = await wx.cloud.callFunction({
        name: 'motor_db',
        data: {
          action: 'get_calculation',
          data: {
            recordId: recordId
          }
        }
      });

      wx.hideLoading();

      if (result.result.success && result.result.data) {
        const recordData = result.result.data;
        console.log('通过ID查询到的计算记录:', recordData);
        
        // 设置机器名称和轴名称
        if (recordData.formData) {
          this.setData({
            machineName: recordData.formData.machineName || '',
            axisName: recordData.formData.axisName || ''
          });
        }
        
        // 准备图表数据
        const speedChartData = this.prepareSpeedChartData(recordData);
        const forceChartData = this.prepareForceChartData(recordData);
        
        this.setData({
          loading: false,
          hasData: true,
          recordData: recordData,
          formData: recordData.formData || {},
          calcResults: recordData.calcResults || {},
          selectedMotor: recordData.selectedMotor || {},
          speedChartData: speedChartData,
          forceChartData: forceChartData,
          modelUrl: recordData.selectedMotor && recordData.selectedMotor.modelUrl ? recordData.selectedMotor.modelUrl : "cloud://cloud1-1ghwzv9vc0d14eef.636c-cloud1-1ghwzv9vc0d14eef-1363443654/model/result.glb"
        });
      } else {
        this.setData({
          loading: false,
          hasData: false,
          errorMessage: result.result.message || '未找到相关计算记录'
        });
      }

    } catch (error) {
      wx.hideLoading();
      console.error('通过ID查询计算记录失败:', error);
      
      this.setData({
        loading: false,
        hasData: false,
        errorMessage: '查询失败，请稍后重试'
      });
    }
  },

  /**
   * 搜索计算记录
   */
  async searchCalculationRecord() {
    try {
      wx.showLoading({
        title: '加载中...'
      });

      const result = await wx.cloud.callFunction({
        name: 'motor_db',
        data: {
          action: 'search_calculation_by_name',
          data: {
            machineName: this.data.machineName,
            axisName: this.data.axisName
          }
        }
      });

      wx.hideLoading();

      if (result.result.success && result.result.data) {
        const recordData = result.result.data;
        console.log('查询到的计算记录:', recordData);
        console.log('recordData.createTime:', recordData.createTime, typeof recordData.createTime);
        
        // 准备图表数据
        const speedChartData = this.prepareSpeedChartData(recordData);
        const forceChartData = this.prepareForceChartData(recordData);
        
        this.setData({
          loading: false,
          hasData: true,
          recordData: recordData,
          formData: recordData.formData || {},
          calcResults: recordData.calcResults || {},
          selectedMotor: recordData.selectedMotor || {},
          speedChartData: speedChartData,
          forceChartData: forceChartData,
          modelUrl: recordData.selectedMotor && recordData.selectedMotor.modelUrl ? recordData.selectedMotor.modelUrl : "cloud://cloud1-1ghwzv9vc0d14eef.636c-cloud1-1ghwzv9vc0d14eef-1363443654/model/result.glb"
        });
      } else {
        this.setData({
          loading: false,
          hasData: false,
          errorMessage: result.result.message || '未找到相关计算记录'
        });
      }

    } catch (error) {
      wx.hideLoading();
      console.error('查询计算记录失败:', error);
      
      this.setData({
        loading: false,
        hasData: false,
        errorMessage: '查询失败，请稍后重试'
      });
    }
  },

  /**
   * 准备速度图表数据
   */
  prepareSpeedChartData(recordData) {
    console.log('准备速度图表数据:', recordData);
    
    // 优先使用保存的图表数据
    if (recordData.speedChartData && recordData.speedChartData.xAxisData && recordData.speedChartData.xAxisData.length > 0) {
      console.log('使用保存的速度图表数据');
      return {
        title: recordData.speedChartData.title || '速度-时间曲线',
        xAxisData: recordData.speedChartData.xAxisData,
        yAxisData: recordData.speedChartData.yAxisData,
        xAxisName: recordData.speedChartData.xAxisName || '时间(s)',
        yAxisName: recordData.speedChartData.yAxisName || '速度(m/s)',
        lineColor: recordData.speedChartData.lineColor || '#ce1b28'
      };
    }
    
    // 如果没有保存的图表数据，尝试从计算结果生成
    if (recordData.calcResults) {
      const calcResults = recordData.calcResults;
      const formData = recordData.formData || {};
      
      // 检查是否有直接的图表数据点
      if (calcResults.speedTimeXPoints && calcResults.speedTimeYPoints) {
        console.log('使用计算结果中的图表数据点');
        return {
          title: '速度-时间曲线（计算结果）',
          xAxisData: calcResults.speedTimeXPoints,
          yAxisData: calcResults.speedTimeYPoints,
          xAxisName: '时间(s)',
          yAxisName: '速度(m/s)',
          lineColor: '#ce1b28'
        };
      }
      
      // 根据基本参数重新生成图表数据
      const totalTime = formData.totalTime || 5.0;
      const maxSpeed = formData.maxSpeed || 1.0;
      const accelTime = parseFloat(calcResults.acceleration) || 1.0;
      const decelTime = parseFloat(calcResults.deceleration) || accelTime;
      const uniformTime = Math.max(0, totalTime - accelTime - decelTime);
      
      console.log('根据参数重新生成图表数据:', { totalTime, maxSpeed, accelTime, decelTime, uniformTime });
      
      // 生成简单的梯形速度曲线
      const timePoints = [];
      const speedPoints = [];
      const pointCount = 20;
      const timeStep = totalTime / pointCount;
      
      for (let i = 0; i <= pointCount; i++) {
        const time = i * timeStep;
        timePoints.push(parseFloat(time.toFixed(2)));
        
        let speed = 0;
        if (time <= accelTime) {
          // 加速阶段
          speed = (maxSpeed / accelTime) * time;
        } else if (time <= accelTime + uniformTime) {
          // 匀速阶段
          speed = maxSpeed;
        } else if (time <= totalTime) {
          // 减速阶段
          const decelStartTime = accelTime + uniformTime;
          speed = maxSpeed - (maxSpeed / decelTime) * (time - decelStartTime);
        }
        speed = Math.max(0, speed);
        speedPoints.push(parseFloat(speed.toFixed(3)));
      }
      
      return {
        title: '速度-时间曲线（重构）',
        xAxisData: timePoints,
        yAxisData: speedPoints,
        xAxisName: '时间(s)',
        yAxisName: '速度(m/s)',
        lineColor: '#ce1b28'
      };
    }
    
    // 默认空数据
    console.log('使用默认空图表数据');
    return {
      title: '速度-时间曲线',
      xAxisData: [0, 1, 2, 3, 4, 5],
      yAxisData: [0, 1, 2, 1, 0, 0],
      xAxisName: '时间(s)',
      yAxisName: '速度(m/s)',
      lineColor: '#ce1b28'
    };
  },

  /**
   * 准备力图表数据
   */
  prepareForceChartData(recordData) {
    console.log('准备力图表数据:', recordData);
    
    // 优先使用保存的图表数据
    if (recordData.forceChartData && recordData.forceChartData.xAxisData && recordData.forceChartData.xAxisData.length > 0) {
      console.log('使用保存的力图表数据');
      return {
        title: recordData.forceChartData.title || '力-时间曲线',
        xAxisData: recordData.forceChartData.xAxisData,
        yAxisData: recordData.forceChartData.yAxisData,
        xAxisName: recordData.forceChartData.xAxisName || '时间(s)',
        yAxisName: recordData.forceChartData.yAxisName || '力(N)',
        lineColor: recordData.forceChartData.lineColor || '#ce1b28'
      };
    }
    
    // 如果没有保存的图表数据，尝试从计算结果生成
    if (recordData.calcResults) {
      const calcResults = recordData.calcResults;
      const formData = recordData.formData || {};
      
      // 检查是否有直接的图表数据点
      if (calcResults.forceTimeXPoints && calcResults.forceTimeYPoints) {
        console.log('使用计算结果中的力图表数据点');
        return {
          title: '力-时间曲线（计算结果）',
          xAxisData: calcResults.forceTimeXPoints,
          yAxisData: calcResults.forceTimeYPoints,
          xAxisName: '时间(s)',
          yAxisName: '力(N)',
          lineColor: '#ce1b28'
        };
      }
      
      // 根据基本参数重新生成图表数据
      const totalTime = formData.totalTime || 5.0;
      const peakForce = parseFloat(calcResults.peakForce) || 500;
      const supportForce = parseFloat(calcResults.supportForce) || 300;
      const accelTime = parseFloat(calcResults.acceleration) || 1.0;
      const decelTime = parseFloat(calcResults.deceleration) || accelTime;
      const uniformTime = Math.max(0, totalTime - accelTime - decelTime);
      
      console.log('根据参数重新生成力图表数据:', { totalTime, peakForce, supportForce, accelTime, decelTime, uniformTime });
      
      // 生成力曲线数据
      const timePoints = [];
      const forcePoints = [];
      const pointCount = 20;
      const timeStep = totalTime / pointCount;
      
      for (let i = 0; i <= pointCount; i++) {
        const time = i * timeStep;
        timePoints.push(parseFloat(time.toFixed(2)));
        
        let force = supportForce; // 基础支撑力
        if (time <= accelTime || time > accelTime + uniformTime) {
          // 加速或减速阶段需要更大的力
          force = peakForce;
        }
        
        // 添加一些随机波动
        const variation = (Math.random() - 0.5) * force * 0.05;
        force = Math.max(0, force + variation);
        forcePoints.push(Math.round(force));
      }
      
      return {
        title: '力-时间曲线（重构）',
        xAxisData: timePoints,
        yAxisData: forcePoints,
        xAxisName: '时间(s)',
        yAxisName: '力(N)',
        lineColor: '#ce1b28'
      };
    }
    
    // 默认空数据
    console.log('使用默认空力图表数据');
    return {
      title: '力-时间曲线',
      xAxisData: [0, 1, 2, 3, 4, 5],
      yAxisData: [300, 500, 500, 500, 300, 300],
      xAxisName: '时间(s)',
      yAxisName: '力(N)',
      lineColor: '#ce1b28'
    };
  },

  /**
   * 格式化数值显示
   */
  formatValue(value, unit = '', defaultValue = '--') {
    if (value === undefined || value === null || value === '' || isNaN(value)) {
      return defaultValue;
    }
    return `${value}${unit}`;
  },

  /**
   * 格式化日期显示
   */
  formatDate(dateString) {
    if (!dateString) return '--';
    try {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    } catch (error) {
      return dateString;
    }
  },

  /**
   * 返回计算列表页
   */
  backToSearch() {
    wx.navigateTo({
      url: '/pages/search/search'
    });
  },

  /**
   * 重新计算
   */
  recalculate() {
    if (!this.data.hasData) return;
    
    // 跳转到计算页面，并传递表单数据
    const formData = this.data.formData;
    const query = Object.keys(formData).map(key => 
      `${key}=${encodeURIComponent(formData[key] || '')}`
    ).join('&');
    
    wx.navigateTo({
      url: `/pages/calculate/calculate?${query}`
    });
  },

  /**
   * 分享此记录 - 获取Excel下载报告
   */
  async shareRecord() {
    if (!this.data.hasData) {
      wx.showToast({
        title: '暂无数据可分享',
        icon: 'none'
      });
      return;
    }
    
    // 检查是否有Excel报告文件ID
    const excelFileId = this.data.recordData.excelFileId;
    if (!excelFileId) {
      wx.showModal({
        title: '提示',
        content: '该记录暂未生成Excel报告，请前往计算页面生成报告后再来分享。',
        confirmText: '去生成',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 跳转到计算页面重新生成
            this.recalculate();
          }
        }
      });
      return;
    }

    // 直接获取已有报告的下载链接
    this.showDownloadLink(excelFileId);
  },



  /**
   * 显示下载链接
   */
  async showDownloadLink(fileID) {
    try {
      wx.showLoading({
        title: '生成下载链接...'
      });

      // 获取临时下载链接
      const result = await wx.cloud.getTempFileURL({
        fileList: [fileID]
      });

      wx.hideLoading();

      if (result.fileList && result.fileList.length > 0 && result.fileList[0].status === 0) {
        const tempFileURL = result.fileList[0].tempFileURL;
        
        // 显示下载链接给用户
        wx.showModal({
          title: '分享报告已生成',
          content: `下载链接有效期2小时,点击"复制链接"可复制到剪贴板`,
          confirmText: '复制链接',
          cancelText: '关闭',
          success: (res) => {
            if (res.confirm) {
              // 复制链接到剪贴板
              wx.setClipboardData({
                data: tempFileURL,
                success: () => {
                  wx.showToast({
                    title: '链接已复制',
                    icon: 'success'
                  });
                },
                fail: (err) => {
                  console.error('复制失败:', err);
                  wx.showToast({
                    title: '复制失败',
                    icon: 'none'
                  });
                }
              });
            }
          }
        });
        
        console.log('分享报告下载链接已生成:', tempFileURL);
      } else {
        throw new Error('获取下载链接失败');
      }
    } catch (error) {
      wx.hideLoading();
      console.error('生成下载链接失败:', error);
      wx.showToast({
        title: '生成链接失败',
        icon: 'none'
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 刷新数据
    this.searchCalculationRecord();
    wx.stopPullDownRefresh();
  },

  /**
   * 用户点击右上角分享或分享按钮
   */
  onShareAppMessage: function (res) {
    console.log('分享触发，来源:', res.from);
    
    const recordId = this.data.recordData?._id;
    const machineName = this.data.machineName || '未知机器';
    const axisName = this.data.axisName || '未知轴';
    
    // 优先使用记录ID，确保分享的准确性
    const sharePath = recordId ? 
      `/pages/search-detail/search-detail?id=${recordId}` : 
      `/pages/search-detail/search-detail?machineName=${encodeURIComponent(machineName)}&axisName=${encodeURIComponent(axisName)}`;
    
    return {
      title: `${machineName} - ${axisName} 电机选型计算结果`,
      path: sharePath,
      imageUrl: '' // 可以添加自定义分享图片
    };
  }
}); 